package main

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"time"
)

func main() {
	// 设置路由
	http.HandleFunc("/callback", callbackHandler)
	http.HandleFunc("/", homeHandler)

	// 配置服务器
	server := &http.Server{
		Addr:         ":8089",
		ReadTimeout:  5 * time.Second,
		WriteTimeout: 10 * time.Second,
	}

	// 启动服务器
	fmt.Printf("🚀 服务已启动，监听端口 8089\n")
	fmt.Printf("👉 测试接口: curl -X POST http://localhost:8089/callback -d '{\"message\":\"test\"}'\n")

	if err := server.ListenAndServe(); err != nil {
		log.Fatalf("❌ 服务器启动失败: %v", err)
	}
}

// 回调接口处理器
func callbackHandler(w http.ResponseWriter, r *http.Request) {
	// 打印请求基本信息
	fmt.Printf("\n=== 收到回调请求 ===\n")
	fmt.Printf("时间: %s\n", time.Now().Format(time.RFC3339))
	fmt.Printf("方法: %s\n", r.Method)
	fmt.Printf("来源IP: %s\n", r.RemoteAddr)
	fmt.Printf("请求头: %v\n", r.Header)

	// 根据Content-Type处理不同格式的请求体
	contentType := r.Header.Get("Content-Type")
	var body interface{}

	switch contentType {
	case "application/json":
		var jsonBody map[string]interface{}
		if err := json.NewDecoder(r.Body).Decode(&jsonBody); err != nil {
			http.Error(w, "无效的JSON数据", http.StatusBadRequest)
			return
		}
		body = jsonBody
	default:
		// 其他类型直接读取原始数据
		data, err := io.ReadAll(r.Body)
		if err != nil {
			http.Error(w, "读取请求体失败", http.StatusBadRequest)
			return
		}
		body = string(data)
	}

	// 打印请求体
	fmt.Printf("请求体: %+v\n", body)
	fmt.Printf("===================\n")

	// 返回成功响应
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]interface{}{
		"status":  "success",
		"message": "回调已接收",
		"data":    body,
	})
}

// 首页处理器
func homeHandler(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}
	w.Header().Set("Content-Type", "text/plain")
	fmt.Fprintf(w, "回调服务运行中\n请访问 /callback 接口")
}
